/* eslint-disable no-restricted-globals */

// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.

import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, CacheFirst, NetworkFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';

clientsClaim();

/**
 * We are not wrapping it in a 'message' event as per the new update.
 * @see https://developers.google.com/web/tools/workbox/modules/workbox-core
 */
self.skipWaiting();

/**
 * Precache all of the assets generated by your build process.
 * Their URLs are injected into the manifest variable below.
 * This variable must be present somewhere in your service worker file,
 * even if you decide not to use precaching. See https://cra.link/PWA
 */
precacheAndRoute(self.__WB_MANIFEST);

// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
// @see https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts
// registerRoute(
//   ({url}) => url.origin === 'https://fonts.googleapis.com',
//   new StaleWhileRevalidate({
//     cacheName: 'google-fonts-stylesheets',
//   })
// );

// Cache the underlying font files with a cache-first strategy for 1 year.
// @see https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts
// registerRoute(
//   ({url}) => url.origin === 'https://fonts.gstatic.com',
//   new NetworkFirst({
//     cacheName: 'google-fonts-webfonts',
//     plugins: [
//       new CacheableResponsePlugin({
//         statuses: [0, 200],
//       }),
//       new ExpirationPlugin({
//         maxAgeSeconds: 60 * 60 * 24 * 365, // 缓存时间：单位秒
//         maxEntries: 30, // 最大缓存数量
//       }),
//     ],
//   })
// );

/**
 * Move api.
 *
 * Caches at: runtime
 */
registerRoute(
  ({url}) => url.origin === 'https://api.openweathermap.org' &&
    url.pathname.startsWith('/data/2.5/onecall'),
  new NetworkFirst({ // 网络优先模式：实时发送网络请求；请求成功，更新缓存；失败则读取缓存；
    cacheName: 'weather-api-response',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({maxEntries: 1}), // Will cache maximum 1 requests.
    ]
  })
);

/**
 * We use CacheFirst for images because, images are not going to change very often,
 * so it does not make sense to revalidate images on every request.
 *
 * @see https://developers.google.com/web/tools/workbox/guides/common-recipes#caching_images
 */
registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst({ // 缓存优先策略：优先读取缓存；如果缓存读取失败，则发起网络请求；
    cacheName: 'images',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  }),
);

// @see https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files
registerRoute(
  ({request}) => request.destination === 'script' ||
    request.destination === 'style',
  new StaleWhileRevalidate({ // 成旧需要重新验证： 则优先读取缓存，无缓存发送请求； 网络请求则回去更新缓存；适用： 拥有最新的资源对应用程序并不重要
    cacheName: 'static-resources',
  })
);


self.addEventListener('activate', event => {
  console.log('self-activate', event)
  // 快速激活 sw，使其能够响应 fetch 事件
  event.waitUntil(clients.claim());
});